package top.truehaku.generator.code.infrastructure.persistence.dao.impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import top.truehaku.generator.code.infrastructure.persistence.dao.ColumnDao;
import top.truehaku.generator.code.infrastructure.persistence.entity.ColumnDO;
import javax.annotation.Resource;
import java.util.List;

@Repository
public class ColumnDaoImpl implements ColumnDao {

    @Resource(name = "template")
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<ColumnDO> selectList(String tableSchema, String tableName) {
        String sql = "SELECT \n" +
                "\tcolumns.table_schema as tableSchema, \n" +
                "\tcolumns.table_name as tableName, \n" +
                "\tcolumns.column_name,\n" +
                "\tcolumns.column_type,\n" +
                "\tcolumns.column_comment,\n" +
                "\tcolumns.ordinal_position,\n" +
                "  CASE WHEN columns.is_nullable = 'yes' THEN '1' ELSE '0' END AS nullable,\n" +
                "  CASE WHEN columns.column_key = 'PRI' THEN '1' ELSE '0' END AS primary_key,\n" +
                "  CASE WHEN columns.column_key = 'UNI' THEN '1' ELSE '0' END AS unique_key,\n" +
                "  CASE WHEN columns.extra = 'auto_increment' THEN '1' ELSE '0' END AS auto_increment\n" +
                "FROM\n" +
                "\tinformation_schema.COLUMNS columns \n" +
                "WHERE\n" +
                "\tcolumns.table_schema = ? \n" +
                "\tAND columns.table_name = ? ";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ColumnDO.class),tableSchema,tableName);
    }
}
